# coding:utf-8
from typing import Optional, Union

from fastapi import APIRouter, Query, Path
from pydantic import BaseModel, Field
from tortoise.expressions import Q

from app.admin.schemas.system import DeptBase, DeptUpdate
from app.admin.service.system.dept import SystemDeptService
from app.core.response import SuccessExtra, Success, Fail


router = APIRouter()


class SearchIn(BaseModel):
    name: str = Field(None, description="用户名称，用于搜索")
    status: Union[str, int] = Field(None, description="用户名称，用于搜索")

@router.post("/dept/list", summary="部门列表")
async def page_list(search: SearchIn):
    # 查询条件
    query = Q()
    if search.name:
        query &= Q(menu_name__contains=search.name)
    if search.status and int(search.status) in [0, 1]:
        query &= Q(status__lt=search.status)
    model_service = SystemDeptService()
    lists = await model_service.tree_list(query)
    return Success(data=lists)


@router.get("/dept/{item_id}", summary="查看部门")
async def get_detail(item_id: int = Path(..., description="部门ID"), ):
    model_service = SystemDeptService()
    item_obj = await model_service.get_id(item_id)
    if not item_obj:
        return Fail(msg="部门不存在")
    item_dict = await item_obj.to_dict(exclude_fields=["password"])
    return Success(data=item_dict)


@router.post("/dept/create", summary="创建部门")
async def create(data_in: DeptBase):
    model_service = SystemDeptService()
    # 查询条件
    query = Q()
    query &= Q(name=data_in.name)
    item = await model_service.find(query)
    if item:
        return Fail(msg="部门名称已存在")
    result = await model_service.create(obj_in=data_in)
    if not result:
        return Fail(msg="创建部门失败")
    return Success(msg="操作成功")


@router.post("/dept/update", summary="更新部门")
async def update(data_in: DeptUpdate):
    model_service = SystemDeptService()
    result = await model_service.update(obj_in=data_in)
    return Success(msg="操作成功")


@router.delete("/dept/delete/{item_id}", summary="删除部门")
async def delete(item_id: int = Path(..., description="部门ID")):
    model_service = SystemDeptService()
    await model_service.remove(item_id)
    return Success(msg="操作成功")
